// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#pragma once

#include <pollux/core/expression_evaluator.h>
#include <pollux/core/i_typed_expr.h>

namespace kumo::pollux::common {
    class ScanSpec;

    /// Represent a logical combination of filters that can be used in row group
    /// skipping.  Filters are put at leaf nodes and internal nodes represents
    /// logical conjunctions between them.
    class MetadataFilter {
    public:
        class LeafNode;

        /// Construct from a ScanSpec and an expression.  The leaf filter nodes
        /// generated will be added to the corresponding position in ScanSpec.
        MetadataFilter(
            ScanSpec &,
            const core::ITypedExpr &,
            core::ExpressionEvaluator *);

        /// Evaluate the filter results based on logical conjunctions tracked in this
        /// object.  `leafNodeResults` could be reused for intermediate results.  The
        /// existing bitmask in `finalResult` will be ANDed with the result we get
        /// from evaluation and stored back.
        void eval(
            std::vector<std::pair<const LeafNode *, std::vector<uint64_t> > > &
            leafNodeResults,
            std::vector<uint64_t> &finalResult);

        std::string toString() const;

    private:
        struct Node;
        struct AndNode;
        struct OrNode;

        std::shared_ptr<Node> root_;
    };
} // namespace kumo::pollux::common
